package com.heima.wemedia.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustException;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.WmThreadLocalUtils;
import com.heima.model.wemedia.dtos.WmMaterialDTO;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import javafx.scene.paint.Material;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
@Slf4j
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {
    @Autowired
    FileStorageService fileStorageService;
    @Value("${file.oss.prefix}")
    String prefix;
    @Value("${file.oss.web-site}")
    String website;

    @Override
    public ResponseResult uploadPicture(MultipartFile multipartFile) {
//1。参数校验
        if (multipartFile == null || multipartFile.getSize() == 0) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);

        }
        //当前线程获取用户ID
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NO_OPERATOR_AUTH);//3000无权限操作
        }


        //校验格式
        String originalFilename = multipartFile.getOriginalFilename();
        if (!checkPicSuffix(originalFilename)) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "请上传正确素材格式,[jpg,jpeg,png,gif]");
        }


//2.上传文件到OSS
        //截取原始文件名后缀  生成UUID   新文件：UUID+文件名后缀

        String fileId = null;
        try {
            String uuid = UUID.randomUUID().toString().replace("-", "");
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));

            fileId = fileStorageService.store(prefix, uuid + suffix, multipartFile.getInputStream());
            log.info("阿里云OSS文件 field：{}", fileId);

        } catch (IOException e) {
            e.printStackTrace();
            log.error("阿里云文件上传失败 failed:{}", e);
            CustException.cust(AppHttpCodeEnum.SERVER_ERROR, "文件上传失败");
        }


//3。创建WmMaterila素材数据
        WmMaterial wmMaterial = new WmMaterial();


//4。保存素材数据
        wmMaterial.setIsCollection((short) 0);
        wmMaterial.setType((short) 0);
        wmMaterial.setCreatedTime(new Date());
//设置文件id
        wmMaterial.setUrl(fileId);
        wmMaterial.setUserId(user.getId());
        save(wmMaterial);
//5。返回值需要将实体类对象返回到前端，并且将url改成完整路径
        wmMaterial.setUrl(website + fileId);

        return ResponseResult.okResult(wmMaterial);
    }

    /**
     * 检查文件格式
     * 目前仅仅支持jpg，jpeg，png，gif上传
     */
    private boolean checkPicSuffix(String path) {
        if (StringUtils.isBlank(path))
            return false;
        List<String> allowSuffix = Arrays.asList("jpg", "jpeg", "png", "gif");

        boolean isAllow = false;
        for (String suffix : allowSuffix) {
            if (path.endsWith(suffix)) {
                isAllow = true;
                break;
            }
        }
        return isAllow;


    }

    /**
     * 素材列表查询
     *
     * @param dto
     * @return
     */

    @Override
    public ResponseResult findList(WmMaterialDTO dto) {

//1.参数校验
        dto.checkParam();
        //2。执行业务查询
        LambdaQueryWrapper<WmMaterial> wrapper = new LambdaQueryWrapper<>();

//3。收藏
        if (dto.getIsCollection() != null && dto.getIsCollection() == 1) {
            wrapper.eq(WmMaterial::getIsCollection, dto.getIsCollection());
        }
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NO_OPERATOR_AUTH);//3000无权限操作
        }

        wrapper.eq(WmMaterial::getUserId, user.getId());

        //4。当前登录用户的素材
        WmUser wmUser = WmThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NO_OPERATOR_AUTH);//3000无权限操作
        }
        //时间降序排序
        wrapper.orderByDesc(WmMaterial::getCreatedTime);
        Page<WmMaterial> pageReq = new Page<>(dto.getPage(), dto.getSize());

        IPage<WmMaterial> pageResult = page(pageReq, wrapper);
        List<WmMaterial> records = pageResult.getRecords();
        for (WmMaterial record : records) {
            record.setUrl(website + record.getUrl());
        }
//封装请求结果
        PageResponseResult pageResponseResult = new PageResponseResult(dto.getPage(), dto.getSize(), pageResult.getTotal());


        //返回结果
        pageResponseResult.setData(records);

        return pageResponseResult;
    }

    @Autowired
    WmNewsMaterialMapper wmNewsMaterialMapper;//操作表

    @Override
    public ResponseResult delPicture(Integer id) {
        //1。校验参数
        if (id == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);//501无效参数
        }
        //2。业务处理
        WmMaterial wmMaterial = getById(id);//更新状态
        if (wmMaterial == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);//1002数据不存在
        }
        LambdaQueryWrapper<WmNewsMaterial> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(WmNewsMaterial::getMaterialId, id);
        Integer count = wmNewsMaterialMapper.selectCount(wrapper);//Mapper自带的方法，查询数量
        if (count > 0) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW);//1003数据不允许被操作
        }

        //删除素材库

        removeById(id);
        //删除图片OSS
        fileStorageService.delete(wmMaterial.getUrl());
        //3。封装结果


        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 收藏与取消收藏
     */
    @Override
    public ResponseResult upateStatus(Integer id, Short type) {
        //1.检验参数
        if (id == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);//501
        }
        //2。更新状态
        WmMaterial wmMaterial = getById(id);//更新状态
        if (wmMaterial == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);//1002数据不存在
        }


        //获取当前用户信息
        Integer count = WmThreadLocalUtils.getUser().getId();
        if (!wmMaterial.getUserId().equals(count)) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW, "不允许收藏不是自己的数据");
        }
        updateById(wmMaterial);//更具你的状态更新id
        wmMaterial.setIsCollection(type);//根据种类决定是否收藏

        //返回结果

        return ResponseResult.okResult();
    }


}
